# conda activate py38

import os
os.environ["QT_QPA_PLATFORM"] = "xcb"
import cv2
import argparse

# Set the log level to ERROR
# cv2.utils.logged_setLogLevel(cv2.utils.LOG_LEVEL_SILENT)
cv2.setLogLevel(0)

# Parse the arguments
parser = argparse.ArgumentParser(description="Camera test")
parser.add_argument("--cam_id", type=int, help="Camera ID")
parser.add_argument("--list", action="store_true", help="List the available camera devices")
args = parser.parse_args()

def print_help():
    print("Usage: python cam_test.py [OPTIONS]")
    print("Options:")
    print("--help: Get help")
    print("--cam_id: Camera ID")
    print("--list: List the available camera devices")


if args.list:
    # Print the available camera devices
    print("Available camera devices:")
    for i in range(10):
        cap = cv2.VideoCapture(i)
        if cap.isOpened():
            print('------------------------------------')
            print(f"Camera ID: {i}")
            print(f"Frame width: {cap.get(cv2.CAP_PROP_FRAME_WIDTH)}")
            print(f"Frame height: {cap.get(cv2.CAP_PROP_FRAME_HEIGHT)}")
            print(f"FPS: {cap.get(cv2.CAP_PROP_FPS)}")
            print()
            cap.release()


if args.cam_id is None:
    print("Error: Camera ID is missing.")
    args.cam_id = int(input("Enter camera ID: "))

if args.cam_id < 0 or args.cam_id > 99:
    print("Error: Invalid camera ID.")
    exit()
else:
    cam_id = args.cam_id
    cap = cv2.VideoCapture(cam_id)

    if not cap.isOpened():
        print("Error: Could not open camera.")
        exit()
    while True:
        ret, frame = cap.read()
        if ret:
            cv2.imshow("Frame", frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            print("Error: Could not read frame.")
            break

    cap.release()
    cv2.destroyAllWindows()
